package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.Ecg;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.service.IEcgService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.utils.HttpUtils;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.vo.EcgVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-04-30
 */

@Api(value = "", tags = "", description = "")
@RestController
@RequestMapping("/health/ecg")
public class EcgController {
    @Autowired
    private IEcgService ecgService;

    @Autowired
    private IUserService userService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result save(@RequestBody Ecg ecg){
        return Result.success(ecgService.save(ecg));
    }

    // 根据ID删除
    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable Integer id){
        return Result.success(ecgService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestBody List<Integer> ids){
        return Result.success(ecgService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll(){
        return Result.success(ecgService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@PathVariable Integer id){
        return Result.success(ecgService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum,@RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "")Long uid,
                           @RequestParam(required = false, defaultValue = "")String startTime,
                           @RequestParam(required = false, defaultValue = "")String endTime){
        QueryWrapper<Ecg> queryWrapper = new QueryWrapper<>();
        queryWrapper.between(ObjectUtil.isNotEmpty(startTime) && ObjectUtil.isNotEmpty(endTime), "CreateDate", startTime, endTime);
        queryWrapper.eq("uid", uid);
        queryWrapper.orderByDesc("CreateDate");
        Page<Ecg> page = ecgService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<EcgVO> lists = MyBeanUtil.collectionCopy(page.getRecords(), EcgVO.class);

        lists.forEach(ecgVO -> {
            if (ecgVO.getDoctorid() != null){
                SysUserEntity user = userService.getRedisByUid(ecgVO.getDoctorid() + "");
                ecgVO.setDoctor(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
            }
        });
        Page<EcgVO> result = new Page<>();
        result.setTotal(page.getTotal());
        result.setRecords(lists);
        return  Result.success(result);
    }

    // 发送请求  生成心电数据
    @PostMapping("/submitElectrocardio")
    @ApiOperation(value = " 发送请求  生成心电数据", notes = " 发送请求  生成心电数据")
    public Result submitElectrocardio(@RequestBody Map params){

        if (!filterFile(params.get("uid"))){
            return Result.error(Constants.CODE_500,"报告生成中,不可重复提交!");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> ECGParams = new HashMap<>();
        String patientId = UUID.randomUUID().toString();
        String CreateDate = sdf.format(new Date());
        String pdTime = sdf.format(new Date());
        SysUserEntity user = userService.getById((Serializable) params.get("uid"));
        String birthday = "";
        if (ObjectUtil.isNotEmpty(user.getCardid())) {
            if (user.getCardid().length() == 15) {
                birthday = "19" + user.getCardid().substring(6, 8) + "-" + user.getCardid().substring(8, 10) + "-"
                        + user.getCardid().substring(10, 12);
            } else if (user.getCardid().length() == 18){
                birthday = user.getCardid().substring(6, 10) + "-" + user.getCardid().substring(10, 12) + "-"
                        + user.getCardid().substring(12, 14);
            }
        }
        // 设置请求参数
        ECGParams.put("orgid", "32c43dd8-5994-4bff-84be-395653fc8e09");
        ECGParams.put("dataType", "12导联心电");
        ECGParams.put("analysisType", "0");
        ECGParams.put("patientId", patientId);
        ECGParams.put("patientName", user.getNickName());
        ECGParams.put("birthday",birthday);
        ECGParams.put("sex", user.getGender());
        ECGParams.put("CreateDate", CreateDate);
        ECGParams.put("pdTime", pdTime);

        String result = getECGResult(ECGParams);
        if (!"error".equals(result)){
            Ecg ecg = new Ecg();
            ecg.setPatientId(patientId);
            ecg.setDoctorid((Integer) params.get("doctorid"));
            ecg.setCreateDate(LocalDateTime.now());
            ecg.setPdTime(LocalDateTime.now());
            ecg.setUid((Integer) params.get("uid"));
            ecg.setFlag("TIANZE");
            ecgService.save(ecg);
            return Result.success(result);
        } else {
            return Result.error(Constants.CODE_500, "请求失败,请联系管理员");
        }
    }

    private Boolean filterFile(Object uid) {
        try {
            String patientId = ecgService.getLastPatientId(uid);
            if (ObjectUtil.isEmpty(patientId)) {
                return true;
            }
            String url = "https://xdsj.oss-cn-beijing.aliyuncs.com/app/nap/singleBluetoothEcg/" + patientId + ".pdf";
            String s = HttpUtils.sendGet(url);
            if (StringUtils.isNotBlank(s)) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    private String getECGResult(Map<String, Object> ecgParams) {
        try {
            String url = "http://taiyi_ecg.tjtzkt.com/submitInfo.aspx";
            HttpHeaders headers = new HttpHeaders();
            MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
            headers.setContentType(type);
            headers.add("Accept", MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> entity = new HttpEntity<String>(JSON.toJSONString(ecgParams), headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            return result.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @ApiOperation(value = "接收参数,保存报告", notes = "接收参数,保存报告")
    @PostMapping("saveInformation")
    public Result saveInformation(@RequestBody JSONObject jsonObject){
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Ecg ecg = new Ecg();
        ecg.setUid(Integer.parseInt(jsonObject.get("user_id").toString()));
        ecg.setDoctorid(null);
        ecg.setConclusion((String) jsonObject.get("conclusion"));
        ecg.setCreateDate(LocalDateTime.parse(jsonObject.get("report_time").toString(), df));
        ecg.setPdTime(LocalDateTime.parse(jsonObject.get("report_time").toString(), df));
        ecg.setFilPath((String) jsonObject.get("file_path"));
        ecg.setPatientId(UUID.randomUUID().toString());
        ecg.setFlag("PENGYANG");

        return Result.success(ecgService.save(ecg));
    }

}

